package com.qsmx.qingqiuticket.app.delegate;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.ClickUtil;
import com.qsmx.core.util.CountDownTimerUtil;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.dimen.DimenUtil;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.core.util.zxing.ZXingUtil;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateSessionListBinding;
import com.qsmx.qingqiuticket.app.delegate.adapter.SessionListAdapter;
import com.qsmx.qingqiuticket.app.entity.LockSessionEntity;
import com.qsmx.qingqiuticket.app.entity.SessionListEntity;
import com.qsmx.qingqiuticket.app.event.CheckTicketWaringEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.fusion.FusionTag;
import com.qsmx.qingqiuticket.app.net.HttpUrl;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;

public class SessionListDelegate extends AtmosDelegate {
    private SessionListEntity mData;
    private SessionListAdapter mAdapter;
    DelegateSessionListBinding mBinding = null;

    public AppCompatImageView ivQrCode;

    private Dialog mQrDialog;
    private String packageId = "";
    private String packageName = "";
    private double packagePrice = 0;
    private int ticketNum = 0;
    private boolean isShowDesc = false;
    private CountDownTimerUtil backTimer;

    public static SessionListDelegate create(String packageId, String packageName, double packagePrice, int ticketNum, boolean isShowDesc) {

        final Bundle args = new Bundle();
        args.putString(FusionTag.PACKAGE_ID, packageId);
        args.putString(FusionTag.PACKAGE_NAME, packageName);
        args.putDouble(FusionTag.PACKAGE_PRICE, packagePrice);
        args.putInt(FusionTag.TICKET_NUM, ticketNum);
        args.putBoolean(FusionTag.IS_SHOW_DESC, isShowDesc);

        final SessionListDelegate delegate = new SessionListDelegate();
        delegate.setArguments(args);
        return delegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        if (args != null) {
            packageId = args.getString(FusionTag.PACKAGE_ID);
            packageName = args.getString(FusionTag.PACKAGE_NAME);
            packagePrice = args.getDouble(FusionTag.PACKAGE_PRICE);
            ticketNum = args.getInt(FusionTag.TICKET_NUM);
            isShowDesc = args.getBoolean(FusionTag.IS_SHOW_DESC, false);

        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_session_list;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

        startCountDownBackTime(60);
        getSessionList(packageId, ticketNum);
        mBinding = DelegateSessionListBinding.bind(rootView);

        mBinding.tvPackageName.setText(packageName);
        mBinding.tvTicketNum.setText((Html.fromHtml(String.format(getString(R.string.ticket_num_tips), ticketNum + ""))));

        mAdapter = new SessionListAdapter(getContext());
        mBinding.rlvSessionList.setAdapter(mAdapter);
        mBinding.rlvSessionList.setLayoutManager(new LinearLayoutManager(getContext()));

        mBinding.tvSuitNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtil.IntegerValueOf(mBinding.tvSuitNum.getText().toString(), 0) <= 1) {
                    mBinding.ivBuyMin.setEnabled(false);
                    mBinding.ivBuyMin.setImageResource(R.mipmap.icon_gary_min);
                } else {
                    mBinding.ivBuyMin.setEnabled(true);
                    mBinding.ivBuyMin.setImageResource(R.mipmap.icon_orange_min);
                }
            }
        });

        mBinding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    getSupportDelegate().pop();
                }
            }
        });

        mBinding.ivBuyMin.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                if (StringUtil.IntegerValueOf(mBinding.tvSuitNum.getText().toString(), 0) > 1) {
                    mBinding.tvSuitNum.setText(StringUtil.IntegerValueOf(mBinding.tvSuitNum.getText().toString(), 0) - 1 + "");
                    mBinding.tvTicketNum.setText((Html.fromHtml(String.format(getString(R.string.ticket_num_tips), ticketNum * StringUtil.IntegerValueOf(mBinding.tvSuitNum.getText().toString(), 0) + ""))));
                    mAdapter.setData(mData.getBody(), ticketNum * StringUtil.IntegerValueOf(mBinding.tvSuitNum.getText().toString(), 0), isShowDesc);
                    mAdapter.notifyDataSetChanged();
                }
            }
        });

        mBinding.ivBuyAdd.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                mBinding.tvSuitNum.setText(StringUtil.IntegerValueOf(mBinding.tvSuitNum.getText().toString(), 0) + 1 + "");
                mBinding.tvTicketNum.setText((Html.fromHtml(String.format(getString(R.string.ticket_num_tips), ticketNum * StringUtil.IntegerValueOf(mBinding.tvSuitNum.getText().toString(), 0) + ""))));
                mAdapter.setData(mData.getBody(), ticketNum * StringUtil.IntegerValueOf(mBinding.tvSuitNum.getText().toString(), 0), isShowDesc);
                mAdapter.notifyDataSetChanged();
            }
        });

        mBinding.tvRefreshSession.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    getSessionList(packageId, ticketNum);
                }
            }
        });

        mBinding.tvRefreshNoSession.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    getSessionList(packageId, ticketNum);
                }
            }
        });

        mBinding.tvMiniProgramTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showQRDialog();
            }
        });

        mAdapter.setonItemClickListener(new SessionListAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                if (ClickUtil.isNotFastClick()) {
                    lockSession(mAdapter.getData().get(position).getSessionId(), mBinding.tvSuitNum.getText().toString());
                }
            }
        });

    }

    @SuppressLint("SetTextI18n")
    public void showQRDialog() {
        if (mQrDialog != null) {
            mQrDialog.dismiss();
        } else {
            mQrDialog = new Dialog(requireContext(), com.qsmx.core.R.style.dialog);
        }

        mQrDialog.setCancelable(false);
        Window window = mQrDialog.getWindow();
        window.setContentView(R.layout.dialog_show_qrcode);
        int width = (int) (DimenUtil.getScreenWidth() * 0.6);
        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);
        mQrDialog.show();

        AppCompatImageView ivClose = window.findViewById(R.id.iv_close);
        ivQrCode = window.findViewById(R.id.iv_qr_code);

        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mQrDialog.dismiss();
            }
        });

        showQrCodeImageView(AtmosPreference.getCustomStringPre(FusionPre.MINI_CODE));

    }

    private void showQrCodeImageView(String qrCode) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = ZXingUtil.generateQRCode(qrCode);
                getProxyActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            ivQrCode.setImageBitmap(bitmap);
                        } catch (Exception e) {

                        }
                    }
                });
            }
        }).start();

    }

    private void lockSession(String sessionId, String reserveQuantity) {
        if (backTimer != null) {
            backTimer.cancel();
        }
        DialogUtil.showLoadingDialog(getContext(), "正在锁定场次...");
        long orderNoTime = System.currentTimeMillis();
        String orderNo = "SP" + AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM) + orderNoTime + StringUtil.getRandomNumString(6);

        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("packageId", packageId);
        params.put("sessionId", sessionId);
        params.put("reserveQuantity", reserveQuantity);
        if (FusionData.mMemData != null) {
            params.put("memberUuid", FusionData.mMemData.getUserId());
        }
        params.put("orderNo", orderNo);

        HttpHelper.RestClientPostRaw(params, HttpUrl.LOCK_SESSION,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<LockSessionEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            LockSessionEntity mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                getSupportDelegate().start(OrderPayDelegate.create(mData.getBody().getOrderNo(),
                                        packageId,
                                        mData.getBody().getSessionId(),
                                        packagePrice,
                                        StringUtil.IntegerValueOf(mBinding.tvSuitNum.getText().toString(), 0),
                                        mData.getBody().getSessionDate() + " " + mData.getBody().getSessionStartTime() + "-" + mData.getBody().getSessionEndTime(),
                                        mData.getBody().getSessionNo(),
                                        mData.getBody().getGiveIntegral() + "",
                                        mData.getBody().getGiveGrowth() + ""));
                            } else {
                                DialogUtil.showCardErrorDialog(getContext(), mData.getHeader().getMessage(), "确定");
                                startCountDownBackTime(60);
                            }
                        } catch (Exception e) {
                            DialogUtil.showCardErrorDialog(getContext(), e.getMessage(), "确定");
                            startCountDownBackTime(60);
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(getContext(), msg, "确定");
                        startCountDownBackTime(60);
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(getContext(), getString(R.string.un_know_net_error), "确定");
                        startCountDownBackTime(60);
                    }
                });

    }

    private void getSessionList(String packageId, int ticketNum) {
        DialogUtil.showLoadingDialog(getContext(), "正在获取场次信息...");
        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("packageId", packageId);

        HttpHelper.RestClientPostRaw(params, HttpUrl.GET_SESSION_LIST,
                new ISuccess() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<SessionListEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                if (mData.getBody() != null && !mData.getBody().isEmpty()) {
                                    mBinding.clNoSession.setVisibility(View.GONE);
                                    mBinding.clSessionList.setVisibility(View.VISIBLE);
                                    mAdapter.setData(mData.getBody(), ticketNum * StringUtil.IntegerValueOf(mBinding.tvSuitNum.getText().toString(), 0), isShowDesc);
                                    mAdapter.notifyDataSetChanged();
                                } else {
                                    mBinding.clNoSession.setVisibility(View.VISIBLE);
                                    mBinding.clSessionList.setVisibility(View.GONE);
                                }
                            } else {
                                mBinding.clNoSession.setVisibility(View.VISIBLE);
                                mBinding.clSessionList.setVisibility(View.GONE);
                                DialogUtil.showCardErrorDialog(SessionListDelegate.this, getContext(), mData.getHeader().getMessage(), "确定", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogUtil.dismissErrorDialog();
                                        getSupportDelegate().pop();
                                    }
                                });
                            }
                        } catch (Exception e) {
                            DialogUtil.showCardErrorDialog(SessionListDelegate.this, getContext(), e.getMessage(), "确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    DialogUtil.dismissErrorDialog();
                                    getSupportDelegate().pop();
                                }
                            });
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(SessionListDelegate.this, getContext(), msg, "确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.dismissErrorDialog();
                                getSupportDelegate().pop();
                            }
                        });
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(SessionListDelegate.this, getContext(), getString(R.string.un_know_net_error), "确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.dismissErrorDialog();
                                getSupportDelegate().pop();
                            }
                        });
                    }
                });
    }

    private void startCountDownBackTime(final long time) {
        if (backTimer != null) {
            backTimer.cancel();
        }
        backTimer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                mBinding.tvTime.setText(String.format(getString(R.string.back_time), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                getSupportDelegate().popTo(HomeDelegate.class, false);
            }
        };
        backTimer.start();// 开始计时
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        startCountDownBackTime(60);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (backTimer != null) {
            backTimer.cancel();
        }
        if (mQrDialog != null && mQrDialog.isShowing()) {
            mQrDialog.dismiss();
        }
        DialogUtil.dismissLoadingDialog();
        DialogUtil.dismissErrorDialog();
    }
}
